package com.tanhua.service;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.tanhua.api.UserInfoService;
import com.tanhua.api.UserService;
import com.tanhua.autoconfig.tmplate.AipTemplate;
import com.tanhua.autoconfig.tmplate.HuanXinTemplate;
import com.tanhua.autoconfig.tmplate.OssTemplate;
import com.tanhua.autoconfig.tmplate.SmsTemplate;
import com.tanhua.config.UserHolder;
import com.tanhua.exceptionhander.CustomException;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.pojo.UserInfo;
import com.tanhua.util.Constants;
import com.tanhua.util.JwtUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class LoginService {

    @Autowired
    private SmsTemplate smsTemplate;
    //注入redis
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //图片上传
    @Autowired
    private OssTemplate ossTemplate;

    @DubboReference
    private UserService userService;

    @DubboReference
    private UserInfoService userInfoService;

    //人脸识别
    @Autowired
    private AipTemplate aipTemplate;

    @Autowired
    private HuanXinTemplate huanXinTemplate;

    @Autowired
    private UserFreezeService userFreezeService;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private MqMessageService mqMessageService;

    //获取验证码
    public ResponseEntity getCode(String phone) {
        User user = userService.findByPhone(phone);
        if (user!=null){
            userFreezeService.checkUserStatus("1",user.getId());
        }
        //设置key
        String key="CHECK_CODE_"+phone;
        //验证验证码是否存在
        if (redisTemplate.opsForValue().get(key)!=null){
            throw new CustomException("验证码未失效");
        }
        //生成六位数的验证码
        String code = RandomUtil.randomNumbers(6);
        System.out.println(code);
        //发送验证码
        smsTemplate.sendSms(phone,code);
        //将验证码存入redis中,五分钟后失效
        redisTemplate.opsForValue().set(key,code, Duration.ofMinutes(5));
        return ResponseEntity.status(200).body("发送成功");
    }

    //账号登录
    public Map<String,Object> loginVerification(Map<String, String> map) {
        boolean isNew=false;
        String phone = map.get("phone");
        //验证码
        String verificationCode = map.get("verificationCode");
        //手机号
        String phoneKey="CHECK_CODE_"+phone;
        //获取redis中的value
        String code = redisTemplate.opsForValue().get(phoneKey);
        if (ObjectUtil.isEmpty(code)){
            throw new CustomException("验证码已失效");
        }
        if (!StrUtil.equals(verificationCode,code)){
            throw new CustomException("验证码不正确");
        }
        //老用户
        String type="01";
        //判断是否是新用户
        User user = userService.findByPhone(phone);
        if (ObjectUtil.isEmpty(user)){
            //新用户
            type="02";
            String password="123456";
            String md5Password = DigestUtils.md5DigestAsHex(password.getBytes());
            //封装user对象
            user=new User();
            user.setMobile(phone);
            user.setPassword(md5Password);
            //新增用户
            userService.save(user);
            //设置成新用户
            isNew=true;
            //重新查询用户
            user = userService.findByPhone(phone);
            //注册环信账号
            String hxUser="hx"+user.getId();
            //123456
            String hxPassword= Constants.INIT_PASSWORD;
            Boolean flag = huanXinTemplate.createUser(hxUser, hxPassword);
            if (flag){
                user.setHxUser(hxUser);
                user.setHxPassword(hxPassword);
                //修改用户信息
                userService.update(user);
            }

        }
        //mq发送信息
        mqMessageService.sendLogService(user.getId(),type,"user",null);
        //删除验证码
        redisTemplate.delete(phoneKey);
        //生成token
        Map stringMap=new HashMap<>();
        stringMap.put("id",Convert.toLong(user.getId()));
        stringMap.put("mobile",phone);
        String token = JwtUtils.getToken(stringMap);
        //生成token
        //String token = AppJwtUtil.getToken(Convert.toLong(user.getId()));
        Map<String,Object> checkMap=new HashMap<>();
        checkMap.put("token",token);
        checkMap.put("isNew",isNew);
        return checkMap;
    }

    //图片上传
    public void head(MultipartFile headPhoto) throws IOException {
        String url;

            //传入文件名和输入流
            url = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
            boolean detect = aipTemplate.detect(url);
            if (!detect){
                throw new CustomException("不包含人脸");
            }else {
                //图片地址更新
                UserInfo userInfo=new UserInfo();
                /*Long userId = BaseContext.getUserId();*/
                Long userId = UserHolder.getUserId();
                userInfo.setId(userId);
                userInfo.setAvatar(url);
                userInfoService.update(userInfo);
            }
    }

    //新增用户信息
    public void loginReginfo(UserInfo userInfo) {
        //获取线程副本中的id
       /* Long userId = BaseContext.getUserId();*/
        Long userId = UserHolder.getUserId();
        //修改id
        userInfo.setId(userId);
        userInfoService.save(userInfo);
    }
}

